package com.bsf.mvc.controller;

import com.bsf.mvc.template.TemplateProvider;
import com.bsf.mvc.web.CustomWebDataBinder;
import com.bsf.serialization.json.JsonProvider;
import com.bsf.util.ExceptionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class SpringController extends BaseController {

    public interface IVisit
    {
        Object invoke(ModelAndView modelAndView);
    }

    /**
     * 页面统一默认拦截器 页面模式
     * 建议参考源码，根据实际业务重写实现。
     * 可加入权限验证，token验证，错误约定等。
     */
    protected ModelAndView pageVisit(IVisit visit)
    {
        ModelAndView modelAndView = null;
        try {
            //页面模板扩展方法
            TemplateProvider tpl = new TemplateProvider();
            request.setAttribute("Html",tpl);
            request.setAttribute("tpl",tpl);

            //默认视图地址为/contoller name/method name,即结构对应一致
            modelAndView = new ModelAndView();
            visit.invoke(modelAndView);

            return modelAndView;
        }
        catch (Exception exp)
        {
            //默认错误拦截处理
//            response.setStatus(500);
//            modelAndView = new ModelAndView("_error");
            request.setAttribute("error", ExceptionUtil.getDetailMessage(exp));
        }
        return  modelAndView;
    }


    /**
     * Json 统一序列化
     * 建议参考源码，根据实际业务情况重写。
     * 可加入token验证，权限验证等，json等输出格式，错误约定等
     */
    protected ModelAndView jsonVisit(IVisit visit)
    {
        ModelAndView modelAndView = new ModelAndView("");
        response.addHeader("Access-Control-Allow-Origin", "*");//跨域支持
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {

            Object jsondata = visit.invoke(modelAndView);
            String json = new JsonProvider().serialize(jsondata);
            response.getWriter().write(json);
            modelAndView.setView(new View() {
                @Override
                public String getContentType() {
                    return null;
                }

                @Override
                public void render(Map<String, ?> map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

                }
            });
        }
        catch (Exception exp)
        {
            //默认错误拦截处理
            //response.setStatus(500);
           try{ response.getWriter().write( ExceptionUtil.getDetailMessage(exp));}catch (Exception e){}
        }
        return modelAndView;
    }



}
